<template>
  <div class="machine-detail">
    <div class="page-title">子页表2—机台详细数据</div>
    
    <div class="filter-row">
      <el-form :inline="true" :model="filterForm" size="small">
        <el-form-item label="渠道">
          <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户标签">
          <el-input v-model="filterForm.user_tag" placeholder="请输入用户标签" type="number" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="游戏ID">
          <el-input v-model="filterForm.game_id" placeholder="请输入游戏ID" type="number" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            style="width: 240px;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>机台详细数据</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="headerCellStyle"
        v-loading="loading"
      >
        <!-- 序号列 -->
        <el-table-column prop="Id" label="序号" width="80" align="center"></el-table-column>
        
        <!-- 渠道列 -->
        <el-table-column prop="channel" label="渠道" width="80" align="center"></el-table-column>
        
        <!-- userTags列 -->
        <el-table-column prop="user_tag" label="用户标签" width="100" align="center"></el-table-column>
        
        <!-- 游戏ID列 -->
        <el-table-column prop="game_id" label="游戏ID" width="100" align="center"></el-table-column>
        
        <!-- 游戏名称列 -->
        <el-table-column prop="game_name" label="游戏名称" width="120" align="center"></el-table-column>
        
        <!-- 机台总计 -->
        <el-table-column label="机台总计" align="center">
          <el-table-column prop="total_play" label="总玩金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_diff" label="总玩-总赢" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ formatRTP(scope.row.total_rtp) }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- 普通模式 -->
        <el-table-column label="普通模式" align="center">
          <el-table-column prop="total_play_normal" label="总玩金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_normal" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_normal" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ formatRTP(scope.row.total_rtp_normal) }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- BELI模式 -->
        <el-table-column label="BELI模式" align="center">
          <el-table-column prop="total_play_beli" label="总玩金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_beli" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_beli" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ formatRTP(scope.row.total_rtp_beli) }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- 超级BELI模式 -->
        <el-table-column label="超级BELI模式" align="center">
          <el-table-column prop="total_play_super" label="总玩金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_super" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_super" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ formatRTP(scope.row.total_rtp_super) }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- 时间列 -->
        <el-table-column prop="create_time" label="时间" width="110" align="center"></el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { gameDetailList } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'MachineDetail',
  mixins: [channelMixin],
  data() {
    return {
      filterForm: {
        channel: null,
        user_tag: '',
        game_id: '',
        dateRange: []
      },
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false
    };
  },
  created() {
    // 渠道选项通过mixin自动加载
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          user_tag: this.filterForm.user_tag ? parseInt(this.filterForm.user_tag) : 0,
          game_id: this.filterForm.game_id ? parseInt(this.filterForm.game_id) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange.length > 0 ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange.length > 1 ? this.filterForm.dateRange[1] : '',
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        const response = await gameDetailList(params)
        
        if (response && response.code === 0) {
          // 处理可能的数据结构差异
          let gameDetails = []
          
          if (response.data && response.data.game_details && Array.isArray(response.data.game_details)) {
            gameDetails = response.data.game_details
          } else if (response.data && Array.isArray(response.data)) {
            gameDetails = response.data
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            gameDetails = response.data.records
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            gameDetails = response.data.list
          } else {
            // 遍历查找数组数据
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                if (Array.isArray(response.data[key])) {
                  gameDetails = response.data[key]
                  break
                }
              }
            }
          }
          
          // 处理字段大小写问题
          if (gameDetails.length > 0) {
            gameDetails = gameDetails.map(item => ({
              ...item,
              // 映射后端字段名到前端期望的字段名
              Id: item.id || item.Id || item.ID,
              channel: item.channel,
              user_tag: item.UserTag || item.user_tag,
              game_id: item.GameId || item.game_id,
              game_name: item.GameName || item.game_name,
              total_play: item.TotalPlay || item.total_play,
              total_win: item.TotalWin || item.total_win,
              total_diff: item.TotalDiff || item.total_diff,
              total_rtp: item.TotalRtp || item.total_rtp,
              total_play_normal: item.TotalPlayNormal || item.total_play_normal,
              total_win_normal: item.TotalWinNormal || item.total_win_normal,
              total_rtp_normal: item.TotalRtpNormal || item.total_rtp_normal,
              total_play_beli: item.TotalPlayBeli || item.total_play_beli,
              total_win_beli: item.TotalWinBeli || item.total_win_beli,
              total_rtp_beli: item.TotalRtpBeli || item.total_rtp_beli,
              total_play_super: item.TotalPlaySuper || item.total_play_super,
              total_win_super: item.TotalWinSuper || item.total_win_super,
              total_rtp_super: item.TotalRtpSuper || item.total_rtp_super,
              create_time: item.CreateTime || item.create_time
            }))
          }
          
          this.tableData = gameDetails
          
          // 处理分页信息
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else {
            this.total = this.tableData.length
          }
        } else {
          this.$message.error(response.msg || response.message || '获取数据失败')
          this.tableData = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取机台详细数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    formatRTP(rtp) {
      if (rtp === null || rtp === undefined || rtp === '') return '--'
      // 如果RTP已经是百分比格式（大于1），直接显示
      if (typeof rtp === 'number') {
        return rtp > 1 ? `${rtp}%` : `${(rtp * 100).toFixed(2)}%`
      }
      // 如果是字符串，检查是否已经包含%号
      if (typeof rtp === 'string') {
        return rtp.includes('%') ? rtp : `${rtp}%`
      }
      return rtp
    },
    headerCellStyle() {
      return {
        backgroundColor: '#e6f1fc',
        color: '#333',
        fontWeight: '600',
        padding: '8px',
        textAlign: 'center'
      };
    },
    resetFilter() {
      this.filterForm = {
        channel: null,
        user_tag: '',
        game_id: '',
        dateRange: []
      }
      this.currentPage = 1
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          user_tag: this.filterForm.user_tag ? parseInt(this.filterForm.user_tag) : 0,
          game_id: this.filterForm.game_id ? parseInt(this.filterForm.game_id) : 0,
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange.length > 0 ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange.length > 1 ? this.filterForm.dateRange[1] : '',
          page: 1,
          page_size: 10000
        }
        
        const response = await gameDetailList(params)
        
        // 处理可能的数据结构差异（与fetchData保持一致）
        let allData = []
        if (response.data && response.data.game_details && Array.isArray(response.data.game_details)) {
          allData = response.data.game_details
        } else if (response.data && Array.isArray(response.data)) {
          allData = response.data
        } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
          allData = response.data.records
        } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
          allData = response.data.list
        } else if (response.data && typeof response.data === 'object') {
          for (let key in response.data) {
            if (Array.isArray(response.data[key])) {
              allData = response.data[key]
              break
            }
          }
        }
        
        // 处理字段映射（与fetchData保持一致）
        if (allData.length > 0) {
          allData = allData.map(item => ({
            ...item,
            // 映射后端字段名到前端期望的字段名
            Id: item.id || item.Id || item.ID,
            channel: item.channel,
            user_tag: item.UserTag || item.user_tag,
            game_id: item.GameId || item.game_id,
            game_name: item.GameName || item.game_name,
            total_play: item.TotalPlay || item.total_play,
            total_win: item.TotalWin || item.total_win,
            total_diff: item.TotalDiff || item.total_diff,
            total_rtp: item.TotalRtp || item.total_rtp,
            total_play_normal: item.TotalPlayNormal || item.total_play_normal,
            total_win_normal: item.TotalWinNormal || item.total_win_normal,
            total_rtp_normal: item.TotalRtpNormal || item.total_rtp_normal,
            total_play_beli: item.TotalPlayBeli || item.total_play_beli,
            total_win_beli: item.TotalWinBeli || item.total_win_beli,
            total_rtp_beli: item.TotalRtpBeli || item.total_rtp_beli,
            total_play_super: item.TotalPlaySuper || item.total_play_super,
            total_win_super: item.TotalWinSuper || item.total_win_super,
            total_rtp_super: item.TotalRtpSuper || item.total_rtp_super,
            create_time: item.CreateTime || item.create_time
          }))
        }
        
        const columns = [
          { prop: 'Id', label: '序号' },
          { prop: 'channel', label: '渠道' },
          { prop: 'user_tag', label: '用户标签' },
          { prop: 'game_id', label: '游戏ID' },
          { prop: 'game_name', label: '游戏名称' },
          { prop: 'total_play', label: '总玩金币' },
          { prop: 'total_win', label: '总赢金币' },
          { prop: 'total_diff', label: '总玩-总赢' },
          { prop: 'total_rtp', label: '总RTP' },
          { prop: 'total_play_normal', label: '普通模式总玩金币' },
          { prop: 'total_win_normal', label: '普通模式总赢金币' },
          { prop: 'total_rtp_normal', label: '普通模式总RTP' },
          { prop: 'total_play_beli', label: 'BELI模式总玩金币' },
          { prop: 'total_win_beli', label: 'BELI模式总赢金币' },
          { prop: 'total_rtp_beli', label: 'BELI模式总RTP' },
          { prop: 'total_play_super', label: '超级BELI模式总玩金币' },
          { prop: 'total_win_super', label: '超级BELI模式总赢金币' },
          { prop: 'total_rtp_super', label: '超级BELI模式总RTP' },
          { prop: 'create_time', label: '时间' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `机台详细数据_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
};
</script>

<style scoped>
.machine-detail {
  width: 100%;
}

.page-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  display: none; /* 隐藏标题，由于表格上方有标题 */
}

.filter-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

::v-deep .el-table th {
  background-color: #e6f1fc;
  padding: 8px 0;
}

::v-deep .el-table td {
  padding: 8px 0;
}

::v-deep .el-table .cell {
  word-break: normal;
  white-space: nowrap;
}

::v-deep .el-table--border th, 
::v-deep .el-table--border td {
  border-right: 1px solid #dcdfe6;
}
</style> 